home *** CD-ROM | disk | FTP | other *** search
- Path: atglab.bls.com!Alun.Champion
- From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
- Newsgroups: comp.lang.c
- Subject: Re: File Size in bytes.
- Date: 22 Jan 1996 22:10:43 GMT
- Organization: Computer People Inc.
- Message-ID: <ALUN.CHAMPION.96Jan22171044@g7240065.bridge.bst.bls.com>
- References: <4e0r59$733@hammerhead.dadd.ti.com>
- NNTP-Posting-Host: bstfirewall.bst.bls.com
- In-reply-to: Sudheer Vemulapalli's message of 22 Jan 1996 20:13:29 GMT
-
- In article <4e0r59$733@hammerhead.dadd.ti.com> Sudheer Vemulapalli <sudheer@dadd.ti.com> writes:
-
- : Is there a simple way to find the exact size of a file. I would like to know of
- : a way to do it other than using ls -l and getting the size field from the
- : output. If there is a UNIX system call or somefunction that returns the file
- : size please let me know.
-
- Though this is phrased in a UNIX specific way (and as such the poster
- should perhaps have asked his question in comp.unix.programmer) it is
- a more general question than that.
-
- In ANSI 'C' the closest you can get is:
-
- #include <stdio.h>
- #include <stdlib.h>
-
- int
- main(void)
- {
- FILE* fp;
- long size;
-
- if ((fp = fopen("SomeFile", "rb")) == 0)
- return EXIT_FAILURE;
-
- if (fseek(fp, 0L, SEEK_END) != 0)
- return EXIT_FAILURE;
-
- if ((size = ftell(fp)) == -1)
- return EXIT_FAILURE;
-
- printf("File size = %ld\n", size);
-
- return EXIT_SUCCESS;
- }
-
- The file needs to be opened in binary mode (which means absolutely nothing
- on the UNIX operating system) for ftell. For a binary stream, the value
- returned by ftell is the number of characters from the beginning of the file.
- Unfortunately on binary streams the standard states that fseek need not
- meaningfully support calls with SEEK_END. It does not say the fseek
- call fails in such situations so in effect this program could print an
- arbitrary value. On most implementations an fseek on a stream, when the
- stream points to a file, should in fact work.
-
- A non-portable (depends on the defintion of portable I suppose) UNIX based
- solution:
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/stat.h>
-
- int
- main(void)
- {
- struct stat st;
-
- if (stat("SomeFile", &st) == -1)
- return EXIT_FAILURE;
-
- printf("File size = %ld\n", (long)st.st_size);
-
- return EXIT_SUCCESS;
- }
-
- Hope one of these helps
- Regards
-
- -A.
- --
- | A.Champion |
-